package br.com.ufpr.sgp;

import org.apache.log4j.Logger;
import org.apache.wicket.Page;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.resource.UrlResourceReference;
import org.wicketstuff.annotation.scan.AnnotatedMountScanner;
import org.wicketstuff.javaee.injection.JavaEEComponentInjector;
import org.wicketstuff.javaee.naming.global.AppJndiNamingStrategy;

import br.com.ufpr.sgp.util.cookies.CookieService;
import br.com.ufpr.sgp.util.session.CustomSessionProvider;
import br.com.ufpr.util.base.AuthorizationStrategy;

public class WicketApplication extends WebApplication {
	private static final Logger log = Logger.getLogger(WicketApplication.class);

	private CookieService cookieService;
	private CustomSessionProvider customSessionProvider;
	

	public WicketApplication() {
	}

	@Override
	protected void init() {
		super.init();

		cookieService = new CookieService();
		log.debug("Cookie service inicializado...");

		log.debug("Inicializando CustomSessionProvider...");
		log.debug("CustomSessionProvider inicializado...");

		getComponentInstantiationListeners().add(
				new JavaEEComponentInjector(this, new AppJndiNamingStrategy(
						"sgp-ejb")));

		log.debug("Registrando listener de seguranÃ§a e autorizaÃ§Ã£o.");
		final AuthorizationStrategy authStrat = new AuthorizationStrategy();
		getSecuritySettings().setAuthorizationStrategy(authStrat);
		getSecuritySettings().setUnauthorizedComponentInstantiationListener(
				authStrat);
		log.debug("Listener de seguranÃ§a e autorizaÃ§Ã£o registrado.");

		log.debug("Configurando Jquery padrÃ£o existente em js/jquery-1.10.2.min.js...");
		getJavaScriptLibrarySettings().setJQueryReference(
				new UrlResourceReference(Url.parse("js/jquery-1.10.2.min.js")));
		log.debug("Jquery padrÃ£o configurado.");

		log.debug("Montando pages anotadas do pacote: br.com.wise.smpgen.web.app ...");
		new AnnotatedMountScanner().scanPackage("br.com.ufpr.sgp").mount(this);
		log.debug("Pages montadas.");
		
		log.debug("Configurado wicket para remover as tags geradas por ele do HTML gerado...");
		getMarkupSettings().setStripWicketTags(true);
		log.debug("Wicket configurado...");

		customSessionProvider = new CustomSessionProvider();
	}

	@Override
	public Class<? extends Page> getHomePage() {
		return HomePage.class;
	}

	@Override
	public Session newSession(final Request request, final Response response) {
		return customSessionProvider.createNewSession(request);
	}

	public static WicketApplication get() {
		return (WicketApplication) WebApplication.get();
	}

	public CookieService getCookieService() {
		return cookieService;
	}
}
